import Cookies from 'js-cookie'
// cookie保存的天数
import config from '@/config'

const {
  cookieExpires,
  projectId
} = config

export const TOKEN_KEY = projectId + 'Token'


//将token信息保存在cookie中，并设置过期时间
export const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, {
    expires: cookieExpires || 1
  })
}

export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) return token
  else return false
}



/**
 * @param {String} url
 * @description 从URL中解析参数
 */
export const getParams = url => {
  const keyValueArr = url.split('?')[1].split('&')
  let paramObj = {}
  keyValueArr.forEach(item => {
    const keyValue = item.split('=')
    paramObj[keyValue[0]] = keyValue[1]
  })
  return paramObj
}



// 比较2个对象是否相同
export const isObjEqual = (o1, o2) => {
  var props1 = Object.getOwnPropertyNames(o1)
  var props2 = Object.getOwnPropertyNames(o2)
  if (props1.length !== props2.length) {
    return false
  }
  for (var i = 0, max = props1.length; i < max; i++) {
    var propName = props1[i]
    if (o1[propName] !== o2[propName]) {
      return false
    }
  }
  return true
}



// 复制文本到剪切板
export const copyContent = (text) => {
  var oInput = document.createElement('input')
  oInput.value = text
  document.body.appendChild(oInput)
  oInput.select() // 选择对象
  document.execCommand('Copy') // 执行浏览器复制命令
  oInput.className = 'oInput'
  oInput.style.display = 'none'
}

export const formatDate = (d, s) => {
  var date = new Date(d)
  var YY = date.getFullYear() + '-'
  var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
  var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
  var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes())
  var ss = (date.getSeconds() < 10 ? ':0' + date.getSeconds() : ':' + date.getSeconds())
  if (s === undefined) {
    return YY + MM + DD + ' ' + hh + mm + ss
  } else {
    return YY + MM + DD + ' ' + hh + mm
  }
}

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const debounce = (fn, t) => {
  let delay = t || 1000
  let timer
  return function () {
    let args = arguments
    if (timer) {
      clearTimeout(timer)
    }

    let callNow = !timer

    timer = setTimeout(() => {
      timer = null
    }, delay)

    if (callNow) fn.apply(this, args)
  }
}

/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const throttle = (fn, t) => {
  let last
  let timer
  let interval = t || 1000
  return function () {
    let args = arguments
    let now = +new Date()
    if (last && now - last < interval) {
      clearTimeout(timer)
      timer = setTimeout(() => {
        last = now
        fn.apply(this, args)
      }, interval)
    } else {
      last = now
      fn.apply(this, args)
    }
  }
}
